package com.zy.stock.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.zy.stock.util.CommonUtils;


@Controller
public class LoginController {

	private Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	/**
	 * 测试用户名:yinpeng 密码:123123
	 * @param String
	 * @param String
	 * @param HttpSession
	 * @return ModelAndView
	 * */
	@RequestMapping(value="login")
	public ModelAndView login(@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "password", defaultValue = "") String password,HttpSession session){
		// 如果sesion不为空,并且session存在属性，直接进入index
		ModelAndView model = new ModelAndView("redirect:/index");
		try{
			// 如果输入用户名密码为空进入登录页面
			if("".equals(username) && "".equals(password)){
				model.setViewName("login");
				return model;
			}
			try{
				UsernamePasswordToken token = new UsernamePasswordToken(username,CommonUtils.MD5(password));
		        token.setRememberMe(false);
		        //获取当前的Subject
		        Subject currentUser = SecurityUtils.getSubject();
		        currentUser.login(token);
			}catch(Exception e){
				logger.error(e.toString());
				// 如果查询时抛出异常返回500页面
				model.setViewName("login");
				model.addObject("message_login","用户名或密码错误");
				return model;
			}
		}catch(Exception e){
			logger.error(e.toString());
		}finally{
			
		}
		return model;
	}
	
	/**
	 * 用户退出
	 * */
	@RequestMapping(value="logout")
	public ModelAndView logout(HttpSession session){
		ModelAndView model = new ModelAndView("login");
		long start = System.currentTimeMillis();
		session.setAttribute("id",null);
		session.setAttribute("user_alias",null);
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		long end = System.currentTimeMillis();
		logger.info("runing login function use times :"+(end - start));
		return model;
	}
}
